package init

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"time"
	"user_server/global"
)

func init() {
	ViperInit()
	MysqlInit()
	RedisInit()
}

func ViperInit() {
	viper.SetConfigFile("./dev.yaml")
	err := viper.ReadInConfig()
	if err != nil {
		panic("读取文件配置失败")
	} else {
		log.Println("读取文件配置成功")
	}
	err = viper.Unmarshal(&global.Config)
	if err != nil {
		panic("解析文件配置失败")
	} else {
		log.Println("解析文件配置成功")
	}
}

func MysqlInit() {
	c := global.Config.Mysql
	var err error
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", c.User, c.Pass, c.Host, c.Port, c.Data)
	global.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		panic(err)
	} else {
		log.Println("mysql init success")
	}
	sqlDB, err := global.DB.DB()

	// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
	sqlDB.SetMaxIdleConns(10)

	// SetMaxOpenConns sets the maximum number of open connections to the database.
	sqlDB.SetMaxOpenConns(100)

	// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
	sqlDB.SetConnMaxLifetime(time.Hour)
}

func RedisInit() {
	global.Rdb = redis.NewClient(&redis.Options{
		Addr:     global.Config.Redis.Addr, // use default Addr
		Password: global.Config.Redis.Pass, // no password set
		DB:       global.Config.Redis.DB,   // use default DB
	})

	pong, err := global.Rdb.Ping(context.Background()).Result()
	if err != nil {
		panic(err)
	} else {
		log.Println(pong)
		log.Println("redis init success")
	}
	// Output: PONG <nil>
}
